﻿using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace _02_TreeViews_and_Value_Converters
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MainWindowLoaded(object sender, RoutedEventArgs e)
        {
            var drivers = Directory.GetLogicalDrives();
            if (drivers != null)
            {
                foreach (var driver in drivers) 
                {
                    var item = new TreeViewItem()
                    {
                        Header = driver,
                        Tag = driver
                    };
                    item.Items.Add(null);
                    item.Expanded += FolderExpanded;
                    FolderView.Items.Add(item);
                }
            }
        }

        private void FolderExpanded(object sender, RoutedEventArgs e)
        {
            var dictionary = sender as TreeViewItem;
            if (dictionary == null || dictionary.Tag == null ||  string.IsNullOrEmpty(dictionary.Tag.ToString())) return;
            var folders = Directory.GetDirectories(dictionary.Tag.ToString() ?? "");
            if (folders == null || folders.Count() == 0) return;
            if (dictionary.Items.Count == 1 && dictionary.Items[0] == null) dictionary.Items.Clear();
            foreach (var folder in folders)
            {
                var item = new TreeViewItem()
                {
                    Header = folder.Split("\\").LastOrDefault(),
                    Tag = folder
                };
                item.Items.Add(null);
                item.Expanded += FolderExpanded;
                dictionary.Items.Add(item);
            }

            var files = Directory.GetFiles(dictionary.Tag.ToString() ?? "");
            if (files == null || files.Count() == 0) return;
            foreach (var file in files)
            {
                var item = new TreeViewItem()
                {
                    Header = file.Split("\\").LastOrDefault(),
                    Tag = file
                };
                dictionary.Items.Add(item);
            }
        }
	}
}